import { ElMessage, ElMessageBox } from "element-plus";
import CryptoJS from "crypto-js";
import { logoutApi } from "@/api/user";
import { useRouter } from "vue-router";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";
const router = useRouter();
const userStore = useUserStore();

const SECRET_KEY = "GuoJie"; // 应通过安全渠道获取

// 加密
export const encryptData = (data) => {
  return CryptoJS.AES.encrypt(JSON.stringify(data), SECRET_KEY).toString();
};

// 解密
export const decryptData = (ciphertext) => {
  const bytes = CryptoJS.AES.decrypt(ciphertext, SECRET_KEY);
  return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
};

export const logout = () => {
  ElMessageBox.confirm("确认退出登录？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      logoutApi();
      sessionStorage.removeItem("token");
      sessionStorage.removeItem("userInfo");
      userStore.setIsLogin(false);
      ElMessage({
        type: "success",
        message: "退出成功",
      });
      location.reload();
    })
    .catch(() => {});
};

export const getToken = () => {
  return sessionStorage.getItem("token");
};
export const isLogin = () => {
  const { isLogin } = storeToRefs(userStore);
  if (isLogin.value) return true;
  if (sessionStorage.getItem("token")) {
    userStore.setIsLogin(true);
    return true;
  }
  return false;
};

export const getDictName = (dictCode, dict) => {
  return dict.find((item) => item.dictCode == dictCode)?.dictName;
};
export const getDictCode = (dictName, dict) => {
  return dict.find((item) => item.dictName == dictName)?.dictCode;
};
export const getUserInfo = () => {
  const { userInfo } = storeToRefs(userStore);
  if (userInfo.value.id) return userInfo;
  const sessionUserInfo = JSON.parse(
    sessionStorage.getItem("userInfo") || "{}"
  );
  if (sessionUserInfo.id) userStore.setUserInfo(sessionUserInfo);
  return sessionUserInfo;
};
